<template>
  <div class="reminders-container">
    <div class="page-header">
      <h1>学习提醒</h1>
      <p>定时提醒，养成好习惯</p>
    </div>
    
    <div class="reminders-content">
      <div class="reminders-header">
        <el-button type="primary" @click="showAddReminderDialog">
          <el-icon><Plus /></el-icon> 添加提醒
        </el-button>
        
        <div class="filter-options">
          <el-select v-model="statusFilter" placeholder="状态" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="已启用" value="active"></el-option>
            <el-option label="已禁用" value="inactive"></el-option>
          </el-select>
          
          <el-select v-model="typeFilter" placeholder="类型" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="每日" value="daily"></el-option>
            <el-option label="每周" value="weekly"></el-option>
            <el-option label="自定义" value="custom"></el-option>
          </el-select>
        </div>
      </div>
      
      <div class="reminders-list" v-if="filteredReminders.length > 0">
        <el-card 
          v-for="(reminder, index) in filteredReminders" 
          :key="index"
          class="reminder-card"
          :class="{ 'inactive-reminder': !reminder.active }"
        >
          <div class="reminder-header">
            <div class="reminder-title">
              <el-icon :class="getReminderIcon(reminder.type).class"><component :is="getReminderIcon(reminder.type).icon" /></el-icon>
              <span>{{ reminder.title }}</span>
            </div>
            <div class="reminder-actions">
              <el-switch
                v-model="reminder.active"
                @change="toggleReminderStatus(index)"
                active-color="#13ce66"
                inactive-color="#ff4949"
              ></el-switch>
              <el-button type="primary" size="small" @click="editReminder(index)">
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button type="danger" size="small" @click="confirmDeleteReminder(index)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
          
          <div class="reminder-content">
            <div class="reminder-time">
              <el-icon><Clock /></el-icon>
              <span>{{ formatReminderTime(reminder) }}</span>
            </div>
            
            <div class="reminder-description" v-if="reminder.description">
              <el-icon><InfoFilled /></el-icon>
              <span>{{ reminder.description }}</span>
            </div>
            
            <div class="reminder-subject" v-if="reminder.subject">
              <el-icon><Reading /></el-icon>
              <span>{{ reminder.subject }}</span>
            </div>
            
            <div class="reminder-repeat">
              <el-icon><Timer /></el-icon>
              <span>{{ formatRepeatType(reminder) }}</span>
            </div>
          </div>
          
          <div class="reminder-footer">
            <div class="reminder-created">
              创建于: {{ reminder.createdAt }}
            </div>
            <div class="reminder-next" v-if="reminder.active">
              下次提醒: {{ calculateNextReminder(reminder) }}
            </div>
          </div>
        </el-card>
      </div>
      
      <div class="empty-reminders" v-else>
        <el-empty description="暂无提醒"></el-empty>
      </div>
    </div>
    
    <!-- 添加/编辑提醒对话框 -->
    <el-dialog
      v-model="reminderDialogVisible"
      :title="isEditing ? '编辑提醒' : '添加提醒'"
      width="500px"
    >
      <el-form :model="reminderForm" label-width="100px" :rules="reminderRules" ref="reminderFormRef">
        <el-form-item label="提醒标题" prop="title">
          <el-input v-model="reminderForm.title" placeholder="请输入提醒标题"></el-input>
        </el-form-item>
        
        <el-form-item label="提醒类型" prop="type">
          <el-select v-model="reminderForm.type" placeholder="请选择提醒类型" style="width: 100%">
            <el-option label="每日提醒" value="daily"></el-option>
            <el-option label="每周提醒" value="weekly"></el-option>
            <el-option label="自定义提醒" value="custom"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="提醒时间" prop="time">
          <el-time-picker
            v-model="reminderForm.time"
            format="HH:mm"
            placeholder="选择时间"
            style="width: 100%"
          ></el-time-picker>
        </el-form-item>
        
        <el-form-item label="重复日期" prop="repeatDays" v-if="reminderForm.type === 'weekly'">
          <el-checkbox-group v-model="reminderForm.repeatDays">
            <el-checkbox label="1">周一</el-checkbox>
            <el-checkbox label="2">周二</el-checkbox>
            <el-checkbox label="3">周三</el-checkbox>
            <el-checkbox label="4">周四</el-checkbox>
            <el-checkbox label="5">周五</el-checkbox>
            <el-checkbox label="6">周六</el-checkbox>
            <el-checkbox label="0">周日</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        
        <el-form-item label="具体日期" prop="specificDate" v-if="reminderForm.type === 'custom'">
          <el-date-picker
            v-model="reminderForm.specificDate"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        
        <el-form-item label="学科" prop="subject">
          <el-select v-model="reminderForm.subject" placeholder="请选择学科" clearable style="width: 100%">
            <el-option 
              v-for="subject in subjects" 
              :key="subject.id" 
              :label="subject.name" 
              :value="subject.name"
            ></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="提醒内容" prop="description">
          <el-input
            v-model="reminderForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入提醒内容"
          ></el-input>
        </el-form-item>
        
        <el-form-item label="启用提醒">
          <el-switch v-model="reminderForm.active"></el-switch>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reminderDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReminderForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteConfirmVisible"
      title="确认删除"
      width="300px"
    >
      <div>确定要删除这个提醒吗？此操作不可恢复。</div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteConfirmVisible = false">取消</el-button>
          <el-button type="danger" @click="deleteReminder">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { 
  Plus, 
  Edit, 
  Delete, 
  Clock, 
  Timer, 
  InfoFilled, 
  Reading,
  Bell,
  Calendar,
  Notification
} from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

// 学科列表
const subjects = [
  { id: 1, name: '数学' },
  { id: 2, name: '物理' },
  { id: 3, name: '化学' },
  { id: 4, name: '语文' },
  { id: 5, name: '英语' },
  { id: 6, name: '历史' },
  { id: 7, name: '地理' },
  { id: 8, name: '生物' }
];

// 状态变量
const statusFilter = ref('');
const typeFilter = ref('');
const reminderDialogVisible = ref(false);
const deleteConfirmVisible = ref(false);
const isEditing = ref(false);
const editingIndex = ref(-1);
const deleteIndex = ref(-1);
const reminderFormRef = ref(null);

// 表单数据
const reminderForm = ref({
  title: '',
  type: 'daily',
  time: new Date(2023, 0, 1, 8, 0),
  repeatDays: ['1', '2', '3', '4', '5'],
  specificDate: null,
  subject: '',
  description: '',
  active: true
});

// 表单验证规则
const reminderRules = {
  title: [
    { required: true, message: '请输入提醒标题', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择提醒类型', trigger: 'change' }
  ],
  time: [
    { required: true, message: '请选择提醒时间', trigger: 'change' }
  ],
  repeatDays: [
    { 
      type: 'array', 
      required: true, 
      message: '请至少选择一天', 
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (reminderForm.value.type === 'weekly' && (!value || value.length === 0)) {
          callback(new Error('请至少选择一天'));
        } else {
          callback();
        }
      }
    }
  ],
  specificDate: [
    { 
      required: true, 
      message: '请选择具体日期', 
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (reminderForm.value.type === 'custom' && !value) {
          callback(new Error('请选择具体日期'));
        } else {
          callback();
        }
      }
    }
  ]
};

// 提醒数据
const reminders = ref([
  {
    id: 1,
    title: '数学作业提醒',
    type: 'daily',
    time: '08:00',
    repeatDays: [],
    specificDate: null,
    subject: '数学',
    description: '完成微积分作业',
    active: true,
    createdAt: '2023-06-15'
  },
  {
    id: 2,
    title: '物理实验准备',
    type: 'weekly',
    time: '14:30',
    repeatDays: ['2', '4'], // 周二和周四
    specificDate: null,
    subject: '物理',
    description: '准备物理实验材料',
    active: true,
    createdAt: '2023-06-16'
  },
  {
    id: 3,
    title: '英语考试',
    type: 'custom',
    time: '09:00',
    repeatDays: [],
    specificDate: '2023-07-20',
    subject: '英语',
    description: '英语期末考试',
    active: true,
    createdAt: '2023-06-18'
  },
  {
    id: 4,
    title: '化学复习',
    type: 'daily',
    time: '20:00',
    repeatDays: [],
    specificDate: null,
    subject: '化学',
    description: '复习有机化学',
    active: false,
    createdAt: '2023-06-20'
  }
]);

// 过滤后的提醒列表
const filteredReminders = computed(() => {
  return reminders.value.filter(reminder => {
    if (statusFilter.value && statusFilter.value === 'active' && !reminder.active) {
      return false;
    }
    if (statusFilter.value && statusFilter.value === 'inactive' && reminder.active) {
      return false;
    }
    if (typeFilter.value && reminder.type !== typeFilter.value) {
      return false;
    }
    return true;
  });
});

// 获取提醒图标
const getReminderIcon = (type) => {
  switch (type) {
    case 'daily':
      return { icon: 'Bell', class: 'daily-icon' };
    case 'weekly':
      return { icon: 'Calendar', class: 'weekly-icon' };
    case 'custom':
      return { icon: 'Timer', class: 'custom-icon' };
    default:
      return { icon: 'Bell', class: 'daily-icon' };
  }
};

// 格式化提醒时间
const formatReminderTime = (reminder) => {
  return reminder.time;
};

// 格式化重复类型
const formatRepeatType = (reminder) => {
  switch (reminder.type) {
    case 'daily':
      return '每天';
    case 'weekly':
      if (reminder.repeatDays.length === 7) {
        return '每天';
      } else if (reminder.repeatDays.length === 5 && 
                reminder.repeatDays.includes('1') && 
                reminder.repeatDays.includes('2') && 
                reminder.repeatDays.includes('3') && 
                reminder.repeatDays.includes('4') && 
                reminder.repeatDays.includes('5')) {
        return '工作日';
      } else if (reminder.repeatDays.length === 2 && 
                reminder.repeatDays.includes('0') && 
                reminder.repeatDays.includes('6')) {
        return '周末';
      } else {
        const dayNames = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
        return reminder.repeatDays.map(day => dayNames[parseInt(day)]).join('、');
      }
    case 'custom':
      return `${reminder.specificDate} 一次性`;
    default:
      return '未知';
  }
};

// 计算下次提醒时间
const calculateNextReminder = (reminder) => {
  const now = new Date();
  const [hours, minutes] = reminder.time.split(':').map(Number);
  
  switch (reminder.type) {
    case 'daily': {
      const next = new Date(now);
      next.setHours(hours, minutes, 0, 0);
      
      if (next <= now) {
        next.setDate(next.getDate() + 1);
      }
      
      return formatDate(next);
    }
    case 'weekly': {
      const today = now.getDay(); // 0-6, 0 is Sunday
      const todayStr = today.toString();
      
      // 如果今天是重复日之一，且当前时间小于提醒时间，则下次提醒是今天
      if (reminder.repeatDays.includes(todayStr)) {
        const next = new Date(now);
        next.setHours(hours, minutes, 0, 0);
        
        if (next > now) {
          return formatDate(next);
        }
      }
      
      // 找到下一个重复日
      let daysToAdd = 1;
      let nextDay = (today + daysToAdd) % 7;
      
      while (!reminder.repeatDays.includes(nextDay.toString()) && daysToAdd < 7) {
        daysToAdd++;
        nextDay = (today + daysToAdd) % 7;
      }
      
      const next = new Date(now);
      next.setDate(next.getDate() + daysToAdd);
      next.setHours(hours, minutes, 0, 0);
      
      return formatDate(next);
    }
    case 'custom': {
      const specificDate = new Date(reminder.specificDate);
      specificDate.setHours(hours, minutes, 0, 0);
      
      if (specificDate <= now) {
        return '已过期';
      }
      
      return formatDate(specificDate);
    }
    default:
      return '未知';
  }
};

// 格式化日期
const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 显示添加提醒对话框
const showAddReminderDialog = () => {
  reminderDialogVisible.value = true;
  isEditing.value = false;
  editingIndex.value = -1;
  
  // 重置表单
  reminderForm.value = {
    title: '',
    type: 'daily',
    time: new Date(2023, 0, 1, 8, 0),
    repeatDays: ['1', '2', '3', '4', '5'],
    specificDate: null,
    subject: '',
    description: '',
    active: true
  };
};

// 编辑提醒
const editReminder = (index) => {
  const reminder = filteredReminders.value[index];
  isEditing.value = true;
  editingIndex.value = index;
  reminderDialogVisible.value = true;
  
  // 设置表单数据
  const [hours, minutes] = reminder.time.split(':').map(Number);
  
  reminderForm.value = {
    title: reminder.title,
    type: reminder.type,
    time: new Date(2023, 0, 1, hours, minutes),
    repeatDays: reminder.repeatDays,
    specificDate: reminder.specificDate ? new Date(reminder.specificDate) : null,
    subject: reminder.subject,
    description: reminder.description,
    active: reminder.active
  };
};

// 确认删除提醒
const confirmDeleteReminder = (index) => {
  deleteIndex.value = index;
  deleteConfirmVisible.value = true;
};

// 删除提醒
const deleteReminder = () => {
  const reminderId = filteredReminders.value[deleteIndex.value].id;
  const originalIndex = reminders.value.findIndex(r => r.id === reminderId);
  
  if (originalIndex !== -1) {
    reminders.value.splice(originalIndex, 1);
    ElMessage.success('删除成功');
  }
  
  deleteConfirmVisible.value = false;
};

// 切换提醒状态
const toggleReminderStatus = (index) => {
  const reminderId = filteredReminders.value[index].id;
  const originalIndex = reminders.value.findIndex(r => r.id === reminderId);
  
  if (originalIndex !== -1) {
    const active = reminders.value[originalIndex].active;
    ElMessage.success(`${active ? '启用' : '禁用'}成功`);
  }
};

// 提交表单
const submitReminderForm = () => {
  reminderFormRef.value.validate((valid) => {
    if (valid) {
      // 格式化时间
      const hours = reminderForm.value.time.getHours().toString().padStart(2, '0');
      const minutes = reminderForm.value.time.getMinutes().toString().padStart(2, '0');
      const formattedTime = `${hours}:${minutes}`;
      
      // 格式化日期
      let formattedDate = null;
      if (reminderForm.value.specificDate) {
        const date = reminderForm.value.specificDate;
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        formattedDate = `${year}-${month}-${day}`;
      }
      
      const reminderData = {
        title: reminderForm.value.title,
        type: reminderForm.value.type,
        time: formattedTime,
        repeatDays: reminderForm.value.repeatDays,
        specificDate: formattedDate,
        subject: reminderForm.value.subject,
        description: reminderForm.value.description,
        active: reminderForm.value.active,
        createdAt: new Date().toISOString().split('T')[0]
      };
      
      if (isEditing.value) {
        // 更新提醒
        const reminderId = filteredReminders.value[editingIndex.value].id;
        const originalIndex = reminders.value.findIndex(r => r.id === reminderId);
        
        if (originalIndex !== -1) {
          reminderData.id = reminders.value[originalIndex].id;
          reminderData.createdAt = reminders.value[originalIndex].createdAt;
          reminders.value[originalIndex] = reminderData;
          ElMessage.success('更新成功');
        }
      } else {
        // 添加提醒
        reminderData.id = Date.now();
        reminders.value.push(reminderData);
        ElMessage.success('添加成功');
      }
      
      reminderDialogVisible.value = false;
    } else {
      return false;
    }
  });
};

// 组件挂载后的处理
onMounted(() => {
  // 这里可以加载提醒数据
});
</script>

<style lang="scss" scoped>
.reminders-container {
  padding: 20px;
  max-width: 90%;
  margin: 0 auto;
  
  .page-header {
    margin-bottom: 20px;
    
    h1 {
      margin: 0 0 10px;
      font-size: 24px;
      color: #303133;
    }
    
    p {
      margin: 0;
      color: #606266;
      font-size: 14px;
    }
  }
  
  .reminders-content {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    padding: 20px;
    
    .reminders-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      
      .filter-options {
        display: flex;
        gap: 10px;
        
        .el-select {
          width: 120px;
        }
      }
    }
    
    .reminders-list {
      .reminder-card {
        margin-bottom: 15px;
        transition: all 0.3s;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        &.inactive-reminder {
          opacity: 0.6;
        }
        
        .reminder-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 15px;
          
          .reminder-title {
            display: flex;
            align-items: center;
            font-size: 16px;
            font-weight: bold;
            color: #303133;
            
            .el-icon {
              margin-right: 10px;
              font-size: 20px;
              
              &.daily-icon {
                color: #409EFF;
              }
              
              &.weekly-icon {
                color: #67C23A;
              }
              
              &.custom-icon {
                color: #E6A23C;
              }
            }
          }
          
          .reminder-actions {
            display: flex;
            align-items: center;
            gap: 10px;
          }
        }
        
        .reminder-content {
          margin-bottom: 15px;
          
          .reminder-time,
          .reminder-description,
          .reminder-subject,
          .reminder-repeat {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
            color: #606266;
            
            &:last-child {
              margin-bottom: 0;
            }
            
            .el-icon {
              margin-right: 8px;
              color: #909399;
            }
          }
        }
        
        .reminder-footer {
          display: flex;
          justify-content: space-between;
          color: #909399;
          font-size: 12px;
        }
      }
    }
    
    .empty-reminders {
      padding: 40px 0;
      text-align: center;
    }
  }
}

@media (max-width: 768px) {
  .reminders-header {
    flex-direction: column;
    align-items: flex-start !important;
    
    .el-button {
      margin-bottom: 10px;
    }
    
    .filter-options {
      width: 100%;
      justify-content: space-between;
    }
  }
  
  .reminder-header {
    flex-direction: column;
    align-items: flex-start !important;
    
    .reminder-title {
      margin-bottom: 10px;
    }
    
    .reminder-actions {
      width: 100%;
      justify-content: flex-end;
    }
  }
  
  .reminder-footer {
    flex-direction: column;
    gap: 5px;
  }
}
</style> 